<template>
  <div>
    <div class="user pd" style="margin-bottom:50px;">
      <div class="art-title-box">
        <input type="text" v-model="title" class="art-title" placeholder="在此输入新闻标题（必须填写）">
      </div>
      <quill-editor ref="myTextEditor" class="news-detail-content pc-bk ql-editor"
        v-model="newsDetail"
        :options="editorOption">
      </quill-editor>
      <!--<div class="input-group">
        <label>新闻副标题：</label>
        <div class="input-group-box"><el-input v-model="subtitle" placeholder="输入新闻副标题"></el-input></div>
      </div>-->
      <div class="input-group mt">
        <label>新闻简介：</label>
        <div class="input-group-box"><el-input v-model="note" type="textarea" :rows="5" placeholder="输入新闻简介（100字以内）"></el-input></div>
      </div>
      <div class="input-group mt">
        <label>分类：</label>
        <div class="input-group-box">
          <el-select v-model="firstLevelCid" placeholder="一级分类" class="cycle-input"  @change="changeFirstLevel">
            <el-option key="" label="请选择一级分类" value=""></el-option>
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="secondLevelCid" placeholder="二级分类" class="cycle-input"  @change="changeSecondLevel">
            <el-option key="" label="请选择二级分类" value=""></el-option>
            <el-option
              v-for="item in secondLevelCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="input-group">
        <label>作者：</label>
        <div class="input-group-box"><el-input v-model="author" placeholder="输入作者"></el-input></div>
      </div>
      <div class="input-group">
        <label>来源：</label>
        <div class="input-group-box"><el-input v-model="source" placeholder="输入来源"></el-input></div>
      </div>
      <div class="input-group">
        <label>排序：</label>
        <div class="input-group-box"><el-input v-model="sort" placeholder="输入排序值" type="number"></el-input><span style="color: red;">排序值越大越靠前，导航的推荐新闻根据此参数进行排序</span></div>
      </div>
      <div class="input-group"  v-if="isAdd">
        <label>是否类目推荐：</label>
        <div class="input-group-box">
          <el-switch
            v-model="isRecommend"
            on-text="是"
            off-text="否"
            on-value="1"
            off-value="0">
          </el-switch>
        </div>
      </div>
      <div class="input-group" v-if="isAdd">
        <label>是否设置精选：</label>
        <div class="input-group-box">
          <el-switch
            v-model="isTop"
            on-text="是"
            off-text="否"
            on-value="1"
            off-value="0">
          </el-switch>
        </div>
      </div>
      <div class="input-group">
        <label>封面图片：</label>
        <div class="input-group-box cover-box">
          <img :src="cover.url" class="cover" v-if="cover.url!==''">
          <div class="el-upload el-upload--picture-card">
            <i class="el-icon-plus"></i>
            <input type="file" id="cover-img" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" class="zi_upload_input" @change="getfile($event)">
          </div>
          <span class="p-tip">* 建议尺寸190*140</span>
        </div>
      </div>
      <div class="input-group">
        <label>发布时间：</label>
        <div class="input-group-box">
          <el-date-picker
            v-model="repub_time"
            type="datetime"
            placeholder="请选择发布时间"
            format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00">
          </el-date-picker>
          <span style="color: red;">* 此参数决定首页的精选内容的顺序，时间越新越靠前</span>
        </div>
      </div>
      <div class="input-group">
        <label>归属于专栏作者：</label>
        <div class="input-group-box">
          <el-select v-model="authorId" filterable placeholder="请选择专栏作者" class="cycle-input">
            <el-option key="0" label="不属于任何作者" value="0"></el-option>
            <el-option
              v-for="item in authorList"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="input-group">
        <label>归属于专题：</label>
        <div class="input-group-box">
          <el-select v-model="subjectId" filterable placeholder="请选择专题" class="cycle-input">
            <el-option key="0" label="不属于任何专题" value="0"></el-option>
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="input-group">
        <label>标记为：</label>
        <div class="input-group-box">
          <el-select v-model="langStatus" filterable placeholder="请选择要标记的版本" class="cycle-input">
            <el-option
              v-for="item in langStatusList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <span style="color: red;">* 此参数决定报名系统中文章的显示，其他的类目里面不受影响</span>
        </div>
      </div>
    </div>
    <preview  v-if="isPreview" :priviewObject="priviewObject" v-on:isCloseView="closeView"></preview>
    <div class="bottom-box" v-if="isAdd">
      <el-button type="primary" size="small" @click="publish" :loading="publishLoading"> 立 即 发 布 </el-button>
      <el-button size="small" @click = 'saveAdd' :loading="saveAddLoading"> 保  存 </el-button>
      <el-button @click="showPreview" size="small"> 预  览 </el-button>
    </div>
    <div class="bottom-box" v-else>
      <el-button size="small" @click = 'saveEditor' :loading="saveEditorLoading"> 保 存 修 改 </el-button>
      <el-button @click="showPreview" size="small"> 预  览 </el-button>
    </div>
    <div class="art-fade" v-if="loadPreview">
      <load class="loadfade"></load>
    </div>
  </div>
</template>
<script>
import api from '../../utils/api'
import apiConfig from '../../utils/apiconfig'
import helper from '../../utils/helper'
import formatdate from '../../utils/formatdate.js'
import { quillEditor } from 'vue-quill-editor'
import preview from './preview'
import load from '../../components/loading'
// import * as Quill from 'quill'
// import ImageResize from 'quill-image-resize-module'
// Quill.register('modules/imageResize', ImageResize)
export default {
  data () {
    return {
      title: '',
      subtitle: '',
      author: '',
      source: '',
      newsDetail: '',
      note: '',
      sort: 0,
      cover: {
        url: '',
        img: ''
      },
      isPublished: true,
      pickerOptions0: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      categoryList: [],
      secondLevelCategoryList: [],
      langStatusList: [
        {
          id: 0,
          name: '中文版'
        },
        {
          id: 1,
          name: '英文版'
        }
      ],
      firstLevelCid: '',
      secondLevelCid: '',
      cid: '',
      isTop: 0,
      isRecommend: 0,
      repub_time: '',
      authorId: '',
      subjectId: '',
      langStatus: 0,
      authorList: [],
      subjectList: [],
      priviewObject: {},
      editorOption: {
        modules: {
          // imageResize: {},
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote'],
            // ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            // [{ 'indent': '-1' }, { 'indent': '+1' }],
            // [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            // [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'font': [] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'align': [] }],
            // ['clean'],
            ['link', 'image', 'video']
          ]
        }
      },
      isPreview: false, // 预览是否出现
      aid: null,
      isAdd: true,
      publishLoading: false,
      saveAddLoading: false,
      saveEditorLoading: false,
      loadPreview: false,
      noteLimit: 600
    }
  },
  components: {
    quillEditor,
    preview,
    load
  },
  created () {
    this.getCategoryLevelOption()
    this.getAuthorList()
    this.getSubjectList()
    var id = this.$route.query.id

    if (id && id !== '' && id !== 'undefined' && id !== null) {
      this.aid = id
      this.isAdd = false
      this.getNewsDetail()
    }
  },
  methods: {
    getfile (event) {
      this.cover.img = event.target.files[0]
      this.cover.url = window.URL.createObjectURL(this.cover.img)
      console.log(this.cover.img)
    },
    getCategoryLevelOption () {
      var param = {
        param: ''
      }
      api.GET(helper.getManageApiUrl(apiConfig.newsCategoryAllLevel), param, res => {
        this.categoryList = res
      }, res => {
        console.log(res)
      })
    },
    getAuthorList () {
      var param = {
        param: ''
      }
      api.GET(helper.getManageApiUrl(apiConfig.getAllSpecialAuthor), param, res => {
        this.authorList = res
      }, res => {
        console.log(res)
      })
    },
    getSubjectList () {
      var param = {
        param: ''
      }
      api.GET(helper.getManageApiUrl(apiConfig.getAllSubject), param, res => {
        this.subjectList = res
      }, res => {
        console.log(res)
      })
    },
    changeFirstLevel (val) {
      console.log(val)
      this.firstLevelCid = val
      this.categoryList.forEach((item) => {
        if (item.id === val) {
          this.secondLevelCategoryList = item.list
        }
      })
    },
    changeSecondLevel (val) {
      this.secondLevelCid = val
    },
    showPreview () {
      this.priviewObject = {
        title: this.title,
        author: this.author,
        source: this.source,
        newsDetail: this.newsDetail,
        published_time: formatdate(new Date())
      }
      this.isPreview = true
    },
    closeView () {
      this.isPreview = false
    },
    saveArt (status) {
      let formData = new FormData()
      formData.append('title', this.title)
      formData.append('subtitle', this.subtitle)
      formData.append('content', this.newsDetail)
      formData.append('author', this.author)
      formData.append('source', this.source)
      formData.append('sort', this.sort)
      formData.append('is_top', this.isTop)
      formData.append('is_recommend', this.isRecommend)
      formData.append('status', status)
      formData.append('note', this.note)
      formData.append('first_level_cid', this.firstLevelCid)
      formData.append('second_level_cid', this.secondLevelCid)
      formData.append('cover_path', this.cover.img)
      formData.append('repub_time', helper.formatDateTime(this.repub_time))
      formData.append('author_id', this.authorId)
      formData.append('subject_id', this.subjectId)
      formData.append('lang_status', this.langStatus)
      let configs = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      api.POST(helper.getManageApiUrl(apiConfig.addNews), formData, configs, res => {
//      api.GET(helper.getManageApiUrl(apiConfig.addNews), videoFormData, res => {
        var type = '保存'
        if (status === 1) {
          type = '发布'
        }
        this.$notify({
          title: '成功',
          message: type + '成功',
          type: 'success',
          duration: 1500
        })
        this.publishLoading = false
        this.saveAddLoading = false
        this.title = ''
        this.subtitle = ''
        this.newsDetail = ''
        this.author = ''
        this.source = ''
        this.sort = 0
        this.note = ''
        this.isTop = 0
        this.isRecommend = 0
        this.firstLevelCid = ''
        this.secondLevelCid = ''
        var cover = document.getElementById('cover-img')
        cover.value = ''
        this.cover.url = ''
        this.repub_time = ''
        this.authorId = 0
        this.subjectId = 0
        // 直接保存到英文
        api.POST(helper.getManageApiUrl(apiConfig.addNews), formData, configs, res => {
          console.log('save news to english edition success')
        }, res => {
          console.log('save news to english edition failed')
        }, true)
      }, res => {
        console.log(res)
      })
    },
    publish () {
//      var title = this.title.replace(/\s/g, '')
//      var author = this.author.replace(/\s/g, '')
//      var source = this.source.replace(/\s/g, '')
//      var note = this.note.replace(/\s/g, '')
      let note = this.note
      let title = this.title
      if (title.length === 0) {
        this.noEmpty('标题不能为空')
        return false
      }
      if (this.newsDetail === '') {
        this.noEmpty('新闻内容不能为空')
        return false
      }
      if (note.length === 0 || note.length > this.noteLimit) {
        this.noEmpty('新闻简介不能为空且必须' + this.noteLimit + '字以内')
        return false
      }
//      if (author.length === 0) {
//        this.noEmpty('新闻作者不能为空')
//        return false
//      }
//      if (source.length === 0) {
//        this.noEmpty('新闻来源不能为空')
//        return false
//      }
      if (this.cover.img === '') {
        this.noEmpty('封面图不能为空')
        return false
      }
      if (this.firstLevelCid === '') {
        this.noEmpty('请选择一级分类')
        return false
      }
      if (this.secondLevelCid === '') {
        this.noEmpty('请选择二级分类')
        return false
      }
      this.publishLoading = true
      this.saveArt(1)
    },
    saveAdd () {
//      var title = this.title.replace(/\s/g, '')
//      var author = this.author.replace(/\s/g, '')
//      var source = this.source.replace(/\s/g, '')
//      var note = this.note.replace(/\s/g, '')
      let note = this.note
      let title = this.title
      if (title.length === 0) {
        this.noEmpty('标题不能为空')
        return false
      }
      if (this.newsDetail === '') {
        this.noEmpty('新闻内容不能为空')
        return false
      }
      if (note.length === 0 || note.length > this.noteLimit) {
        this.noEmpty('新闻简介不能为空且必须' + this.noteLimit + '字以内')
        return false
      }

//      if (author.length === 0) {
//        this.noEmpty('新闻作者不能为空')
//        return false
//      }
//      if (source.length === 0) {
//        this.noEmpty('新闻来源不能为空')
//        return false
//      }
      if (this.cover.img === '') {
        this.noEmpty('封面图不能为空')
        return false
      }
      if (this.firstLevelCid === '') {
        this.noEmpty('请选择一级分类')
        return false
      }
      if (this.secondLevelCid === '') {
        this.noEmpty('请选择二级分类')
        return false
      }
      this.saveAddLoading = true
      this.saveArt(0)
    },
    getNewsDetail () { // 修改新闻时，首先获取新闻内容
      this.loadPreview = true
      var param = {
        id: this.aid
      }
      api.GET(helper.getManageApiUrl(apiConfig.newsDetail), param, res => {
        var resData = res
        this.firstLevelCid = resData.first_level_cid
        this.secondLevelCid = resData.second_level_cid
        this.title = resData.title
        this.subtitle = resData.subtitle
        this.author = resData.author
        this.source = resData.source
        this.sort = resData.sort
        this.isTop = resData.is_top
        this.isRecommend = resData.is_recommend
        this.note = resData.note
        this.newsDetail = resData.content
        this.cover.url = resData.cover_path
        this.cover.img = resData.cover_path
        this.repub_time = resData.repub_time
        this.authorId = resData.author_id
        this.subjectId = resData.subject_id
        this.langStatus = resData.lang_status
        // 初始话二级分类
        let _this = this
        this.categoryList.forEach((item) => {
          if (item.id === this.firstLevelCid) {
            _this.secondLevelCategoryList = item.list
          }
        })
        this.loadPreview = false
      }, res => {
        this.noEmpty('获取数据失败')
      })
    },
    saveEditor () {
//      var title = this.title.replace(/\s/g, '')
//      var note = this.note.replace(/\s/g, '')
//      var author = this.author.replace(/\s/g, '')
//      var source = this.source.replace(/\s/g, '')
      let author = this.author
      let source = this.source
      let note = this.note
      let title = this.title
      if (title.length === 0) {
        this.noEmpty('标题不能为空')
        return false
      }
      if (this.newsDetail === '') {
        this.noEmpty('新闻内容不能为空')
        return false
      }
      if (note.length === 0 || note.length > this.noteLimit) {
        this.noEmpty('新闻简介不能为空且必须' + this.noteLimit + '字以内')
        return false
      }
//      if (author.length === 0) {np
//        this.noEmpty('新闻作者不能为空')
//        return false
//      }
//      if (source.length === 0) {
//        this.noEmpty('新闻来源不能为空')
//        return false
//      }
      if (this.cover.img === '') {
        this.noEmpty('封面图不能为空')
        return false
      }
      if (this.firstLevelCid === '') {
        this.noEmpty('请选择一级分类')
        return false
      }
      if (this.secondLevelCid === '') {
        this.noEmpty('请选择二级分类')
        return false
      }
      this.saveEditorLoading = true
      let formData = new FormData()
      formData.append('id', this.aid)
      formData.append('title', this.title)
      formData.append('subtitle', this.subtitle)
      formData.append('content', this.newsDetail)
      formData.append('is_recommend', this.isRecommend)
      formData.append('author', author)
      formData.append('source', source)
      formData.append('sort', this.sort)
      formData.append('note', note)
      formData.append('first_level_cid', this.firstLevelCid)
      formData.append('second_level_cid', this.secondLevelCid)
      formData.append('cover_path', this.cover.img)
      formData.append('repub_time', helper.formatDateTime(this.repub_time))
      formData.append('author_id', this.authorId)
      formData.append('subject_id', this.subjectId)
      formData.append('lang_status', this.langStatus)
      let configs = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      console.log(formData)
      api.POST(helper.getManageApiUrl(apiConfig.updateNews), formData, configs, res => {
        this.$notify({
          title: '成功',
          message: '修改已保存',
          type: 'success',
          duration: 1500
        })
        this.saveEditorLoading = false
        // this.$router.push('/index/news/list/51')
        window.history.go(-1)
      }, res => {
        this.noEmpty(res.msg)
      })
    },
    noEmpty (tip) {
      this.$notify({
        title: '提示',
        message: tip,
        type: 'error',
        duration: 1500
      })
    }
  }
}
</script>
<style>
.art-fade {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99;
  background: rgba(255, 255, 255, 0.7);
  padding-top: 5%;
}
.quill-editor .ql-container {
  height: 480px;
  line-height: 1.7;
}
.quill-editor .ql-container p, .quill-editor .ql-container h1, .quill-editor .ql-container h2{
  padding: 6px 0;
}
.quill-editor .ql-container li {
  padding: 3px 0;
}
.quill-editor .ql-container ul, .quill-editor .ql-container ol {
  padding: 6px 0;
}
.ql-snow.ql-container .ql-editor pre {
    margin-bottom: 6px;
    margin-top: 6px;
    padding: 8px 15px;
}
.ql-snow.ql-container .ql-editor blockquote {
  border-left: 4px solid #ccc;
  margin-bottom: 8px;
  margin-top: 8px;
  padding: 5px 16px;
}
.input-group-box .el-upload--picture-card {
  position: relative;
  width: 100px;
  height: 100px;
}
.input-group-box img.cover {
  width: 95px;
  height: 71px;
  display: block;
  margin-bottom: 10px;
}
.input-group-box .el-upload--picture-card i {
  position: absolute;
  top: 35px;
  left: 35px;
}
.el-upload--picture-card .zi_upload_input {
  position: absolute;
  display: inline-block;
  width: 100%;
  height: 100%;
  opacity: 0;
  top: 0;
  left: 0;
  cursor: pointer;
}
.input-group .input-group-box label.el-switch {
  width: auto;
  line-height: auto;
  margin-top: 7px;
  vertical-align: top
}
.art-title-box {
  margin-bottom: 8px;
  padding: 0px 25px;
}
.art-title{
  width: 100%;
  border: none;
  background-color: transparent;
  color: #000;
  font-size: 22px;
  height: 45px;
  line-height: 45px;
}
.input-group.mt {
  margin-top: 24px;
}
.bottom-box {
    position: fixed;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    left: 180px;
    background: #f2f2f2;
    border-top: 1px solid #dedede;
    height: 50px;
    text-align: right;
    line-height: 50px;
    padding-right: 350px;
}
.bottom-box .el-button {
  margin-left: 25px;
}
.cover-box .p-tip {
  display: inline-block;
  color: red;
  font-size: 12px;
  margin-top: 80px;
  margin-left: 10px;
}
</style>
